package com.asurplus.common.utils;

import com.asurplus.common.minio.MinioUtil;
import com.asurplus.common.vo.BackupRespVO;
import com.asurplus.entity.BackupLog;
import com.asurplus.mapper.BackupLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 备份文件处理
 *
 * @author asurplus
 */
@Slf4j
@Component
public class BackupFileUtil {

    @Autowired
    private MinioUtil minioUtil;
    @Resource
    private BackupLogMapper backupLogMapper;

    @Async
    public void uploadBackupFile(BackupRespVO respVO, BackupLog backupLog) {
        String filePath = backupLog.getFilePath();
        String path = minioUtil.uploadFile(respVO.getFile(), null);
        if (null == path) {
            log.error("上传备份文件到minio失败：file：{}", filePath);
            return;
        }
        // 更新filePath
        backupLog.setFilePath(path);
        backupLog.setStatus(2);
        backupLogMapper.updateById(backupLog);
        // 删除文件
        if (!backupLog.getIsDelete()) {
            return;
        }
        try {
            respVO.getFile().delete();
        } catch (Exception e) {
            log.error("删除磁盘备份文件失败：file：{}， msg：{}", filePath, e.getMessage());
        }
    }
}
